package com.newviews.tcmip.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.sql.*;
@Slf4j
@Component
public class JdbcUtils {
    /**
     * 返回数据库连接
     */
    public Connection getConnection(String url,String className,String username,String password) {
        Connection con = null;
        try {
            Class.forName(className);
            con = DriverManager.getConnection(url,username,password);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            log.error("数据库连接失败：" + e.getMessage());
        }
        return con;
    }

    /**
     * 关闭连接
     */
    public void closeConn(Connection con, Statement statement, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
